package com.deyang.ui.activity;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.deyang.maillist.R;
import com.deyang.ui.fragment.HomePageFragment;
import com.deyang.ui.fragment.MyFragment;
import com.deyang.util.Logger;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends BaseActivity implements View.OnClickListener {

    private static final String CURRENT_FRAGMENT = "STATE_FRAGMENT_SHOW";

    @BindView(R.id.fl_home)
    FrameLayout flHome;

    @BindView(R.id.ll_homePage)
    LinearLayout llHomePage;
    @BindView(R.id.ll_my)
    LinearLayout llMy;

    @BindView(R.id.iv_homePage)
    ImageView ivHomePage;
    @BindView(R.id.tv_homePage)
    TextView tvHomePage;

    @BindView(R.id.iv_my)
    ImageView ivMy;
    @BindView(R.id.tv_my)
    TextView tvMy;


    private boolean isSelectHomePage = false;

    private FragmentManager fragmentManager;
    private List<Fragment> fragments = new ArrayList<>();
    private Fragment currentFragment;
    private int currentIndex = 0;

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }

    @Override
    protected void processLogic(Bundle savedInstanceState) {
        // 初始化fragment 实现可切换
        fragmentManager = getSupportFragmentManager();
        if (savedInstanceState != null) {
            // “内存重启”时调用
            //获取“内存重启”时保存的索引下标
            currentIndex = savedInstanceState.getInt(CURRENT_FRAGMENT, 0);

            //注意，添加顺序要跟下面添加的顺序一样！！！！
            fragments.removeAll(fragments);
            fragments.add(fragmentManager.findFragmentByTag(0 + ""));
            fragments.add(fragmentManager.findFragmentByTag(1 + ""));

            //恢复fragment页面
            restoreFragment();

        } else {      //正常启动时调用
            fragments.add(new HomePageFragment());
            fragments.add(new MyFragment());
            showFragment();

            setFragmentSelect(true);
        }
    }

    /**
     * 设置选择项
     *
     * @param isHomePage 是否是首页
     */
    private void setFragmentSelect(boolean isHomePage) {
        if (isHomePage) {
            tvHomePage.setTextColor(getColorRes(R.color.main_bottom_tv_select));
            tvMy.setTextColor(getColorRes(R.color.main_bottom_tv_normal));
            ivHomePage.setBackgroundResource(R.drawable.home_page2);
            ivMy.setBackgroundResource(R.drawable.my1);

        } else {
            tvHomePage.setTextColor(getColorRes(R.color.main_bottom_tv_normal));
            tvMy.setTextColor(getColorRes(R.color.main_bottom_tv_select));
            ivHomePage.setBackgroundResource(R.drawable.home_page1);
            ivMy.setBackgroundResource(R.drawable.my2);
        }
        isSelectHomePage = isHomePage;
    }


    @OnClick({
            R.id.ll_homePage,
            R.id.ll_my,
    })
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_homePage:
                if (!isSelectHomePage) {
                    currentIndex = 0;
                    showFragment();
                    setFragmentSelect(true);
                }
                break;
            case R.id.ll_my:
                if (isSelectHomePage) {
                    currentIndex = 1;
                    showFragment();
                    setFragmentSelect(false);
                }
                break;
        }
    }


    /**
     * 使用show() hide()切换页面
     * 显示fragment
     */
    private void showFragment() {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        //如果之前没有添加过
        Fragment fragment = fragments.get(currentIndex);
        Logger.i(TAG, "fragmentName:" + fragment.getClass().getName());
        if (!fragment.isAdded()) {
            if (currentFragment != null) {
                transaction
                        .hide(currentFragment)
                        //第三个参数为添加当前的fragment时绑定一个tag
                        .add(R.id.fl_home, fragment, "" + currentIndex);
            } else {
                //第三个参数为添加当前的fragment时绑定一个tag
                transaction.add(R.id.fl_home, fragment, "" + currentIndex);
            }
        } else {
            transaction
                    .hide(currentFragment)
                    .show(fragment);
        }
        currentFragment = fragment;
        transaction.commit();
    }

    /**
     * 恢复fragment
     */
    private void restoreFragment() {
        FragmentTransaction mBeginTreansaction = fragmentManager.beginTransaction();
        for (int i = 0; i < fragments.size(); i++) {
            if (i == currentIndex) {
                mBeginTreansaction.show(fragments.get(i));
            } else {
                mBeginTreansaction.hide(fragments.get(i));
            }
        }
        mBeginTreansaction.commit();
        //把当前显示的fragment记录下来
        currentFragment = fragments.get(currentIndex);
    }


    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            showToastInfo("再按一次退出程序");
            exitTime = System.currentTimeMillis();
        } else {
            finish();
            mApp.finishAllActivity();
            System.exit(0);
        }
    }

}
